package com.financialDog.javaTool.controller.fileManage;


import com.financialDog.javaTool.controller.reportTools.ReportMergeToolController;
import com.financialDog.javaTool.services.fileManage.FileManageService;
import com.financialDog.javaTool.view.fileManager.FileManageView;
import com.xwintop.xcore.util.javafx.FileChooserUtil;
import com.xwintop.xcore.util.javafx.JavaFxViewUtil;
import com.xwintop.xcore.util.javafx.TooltipUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class FileManageController extends FileManageView {

    public static final String FXML = "/com/financialDog/javaTool/fxmlView/reportTools/FileManage.fxml";

    private FileManageService fileManageService = new FileManageService(this);

    private ObservableList<Map<String, String>> tableData = FXCollections.observableArrayList();

    private ReportMergeToolController reportMergeToolController;

    final static String tableColumnName = "name";
    final static String tableColumnType = "type";
    final static String tableColumnYear = "yearType";
    final static String tableColumnTime = "time";
    final static String tableColumnFilePath = "filePath";

    public static FXMLLoader getFXMLLoader() {
        return new FXMLLoader(FileManageController.class.getResource(FXML));
    }

    private String[] filtrationTypeChoiceBoxStrings = new String[] { "所有","资产负债表","现金流量表", "利润表"};

    private String[] yearChoiceBoxStrings = new String[] {"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022"};

    private String[] timeChoiceBoxStrings = new String[] { "整年","一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initView();
        initEvent();
        initService();
    }

    private void initView() {
        JavaFxViewUtil.setTableColumnMapValueFactory(nameTableColumn, "name");
        JavaFxViewUtil.setTableColumnMapAsChoiceBoxValueFactory(yearTableColumn, "yearType",yearChoiceBoxStrings);
        JavaFxViewUtil.setTableColumnMapAsChoiceBoxValueFactory(typeTableColumn, "type", filtrationTypeChoiceBoxStrings);
        JavaFxViewUtil.setTableColumnMapAsChoiceBoxValueFactory(timeTableColumn, "time", timeChoiceBoxStrings);
        nameTableColumn.prefWidthProperty().bind(fileManageTableView.widthProperty().multiply(0.6));
        yearTableColumn.prefWidthProperty().bind(fileManageTableView.widthProperty().multiply(0.1));
        typeTableColumn.prefWidthProperty().bind(fileManageTableView.widthProperty().multiply(0.1));
        timeTableColumn.prefWidthProperty().bind(fileManageTableView.widthProperty().multiply(0.1));
        operateTableColumn.prefWidthProperty().bind(fileManageTableView.widthProperty().multiply(0.1));

        fileManageTableView.setItems(tableData);
        fileManageTableView.getColumns().remove(nameTableColumn);
        fileManageTableView.getColumns().remove(yearTableColumn);
        fileManageTableView.getColumns().remove(typeTableColumn);
        fileManageTableView.getColumns().remove(timeTableColumn);
        fileManageTableView.getColumns().remove(operateTableColumn);

        operateTableColumn.setCellFactory(
            new Callback<TableColumn<Map<String, String>, String>, TableCell<Map<String, String>, String>>() {
                @Override
                public TableCell<Map<String, String>, String> call(TableColumn<Map<String, String>, String> param) {
                    return new TableCell<Map<String, String>, String>() {
                        @Override
                        protected void updateItem(String item, boolean empty) {
                            super.updateItem(item, empty);
                            this.setText(null);
                            this.setGraphic(null);
                            if (!empty) {
                                Integer removeIndex = this.getIndex();
                                Button deleteButton = new Button("删除");
                                this.setContentDisplay(ContentDisplay.CENTER);
                                deleteButton.setOnMouseClicked((me) -> {
                                    try {
                                        tableData.remove(tableData.get(removeIndex));
                                        fileManageTableView.refresh();
                                        TooltipUtil.showToast("删除成功");
                                    } catch (Exception e) {
                                        TooltipUtil.showToast("删除失败：" + e.getMessage());
                                    }
                                });
                                this.setGraphic(deleteButton);
                            }
                        }
                    };
                }
            });


        nameTableColumn.setStyle( "-fx-alignment: CENTER;");
        yearTableColumn.setStyle( "-fx-alignment: CENTER;");
        typeTableColumn.setStyle( "-fx-alignment: CENTER;");
        timeTableColumn.setStyle( "-fx-alignment: CENTER;");
        operateTableColumn.setStyle( "-fx-alignment: CENTER;");


        fileManageTableView.getColumns().add(nameTableColumn);
        fileManageTableView.getColumns().add(yearTableColumn);
        fileManageTableView.getColumns().add(typeTableColumn);
        fileManageTableView.getColumns().add(timeTableColumn);
        fileManageTableView.getColumns().add(operateTableColumn);

    }

    private void initEvent() {

        // 右键菜单
        MenuItem mnuSavePluginConfig = new MenuItem("保存配置");
//        mnuSavePluginConfig.setOnAction(ev -> {
//            try {
//                PluginManager.getInstance().saveToFile();
//                TooltipUtil.showToast("保存配置成功");
//            } catch (Exception ex) {
//                log.error("保存插件配置失败", ex);
//            }
//        });
//
//        ContextMenu contextMenu = new ContextMenu(mnuSavePluginConfig);
//        pluginDataTableView.setContextMenu(contextMenu);
//
//        // 搜索
//        selectPluginTextField.textProperty().addListener((_ob, _old, _new) -> {
//            pluginManageService.searchPlugin(_new);
//        });
    }

    private void initService() {
        //pluginManageService.getPluginList();
    }

    public void setReportMergeToolController(ReportMergeToolController reportMergeToolController){
        this.reportMergeToolController = reportMergeToolController;

        //初始化数据
	    initData();
    }

    @FXML
    private void fileAddAction(ActionEvent event) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        File file = FileChooserUtil.chooseFile();
        if (file == null){
            TooltipUtil.showToast("文件不存在");
            return;
        }
        //获取type 有点问题，建议修改
//        String fileType = FileTypeUtil.getType(file);
//        if (!(fileType.equals("xls") || fileType.equals("xlsx"))){
//            TooltipUtil.showToast("请输入正确的文件格式,目前只支持xls,xlsx");
//            return ;
//        }
        String fileName = file.getName();
        hashMap.put(tableColumnName, fileName);
        hashMap.put(tableColumnType, "所有");
        hashMap.put(tableColumnYear, "2019");
        hashMap.put(tableColumnTime, "整年");
        hashMap.put(tableColumnFilePath, file.getAbsolutePath());
        tableData.add(hashMap);

        reportMergeToolController.setTableData(tableData);
    }


    public ObservableList<Map<String, String>> getTableData(){
        return tableData;
    }


    private void initData(){
    	if (reportMergeToolController == null){
    		TooltipUtil.showToast("控制器没有初始化");
	    }
    	tableData.addAll(reportMergeToolController.getTableData());
    }

}
